package com.sgcc.ln.pmos.common.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.ActionMode;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.sgcc.pmos.nativesdk.R;
import com.sgcc.ln.pmos.common.utils.InputFilterUtils;
import com.sgcc.ln.pmos.common.utils.SysUtil;


import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressLint("AppCompatCustomView")
public class MyEditText extends EditText {

    public MyEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        setEditTextFilters(attrs);
    }

    public MyEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setEditTextFilters(attrs);
    }

    public MyEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        setEditTextFilters(attrs);
    }

    InputFilter[] fileList;

    public void setEditTextFilters(AttributeSet attrs) {
        TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.MyEditText);
        canCopy = typedArray.getBoolean(R.styleable.MyEditText_canCopy, false);
        canNewLine = typedArray.getBoolean(R.styleable.MyEditText_canNewLine, false);
        filterType = typedArray.getInt(R.styleable.MyEditText_filterType, 0);
        setCanCopy(canCopy);
        setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (!canNewLine && event != null) {
                    return event.getKeyCode() == KeyEvent.KEYCODE_ENTER;
                }
                return false;
            }
        });

//        WeakReference<Context> weak = new WeakReference<Context>(getContext());
//        InputFilter[] filters = getFilters();
//        ArrayList<InputFilter> filters1 = new ArrayList<>();
//        for (InputFilter filter : filters) {
//            filters1.add(filter);
//        }
//        filters1.add(setFilter(weak.get()));
//        InputFilter[] objects = (InputFilter[]) filters1.toArray();
//        setFilters(objects);

//        if (getFilters() != null && getFilters().length > 0) {
//            fileList = new InputFilter[getFilters().length + 1];
//            for (int i = 0; i < getFilters().length; i++) {
//                fileList[i] = getFilters()[i];
//            }
//            fileList[fileList.length - 1] = setFilter(weak.get());
//            setFilters(fileList);
//
//        } else {
//            fileList = new InputFilter[]{setFilter(weak.get())};
//            setFilters(fileList);
//        }
        if (filterType == 0) {
            addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                    String string = getText().toString();
                    if (!TextUtils.isEmpty(SysUtil.checkSQL(string))) {
                        setText(string.replace(SysUtil.checkSQL(string), ""));
                        try {
                            setSelection(start);
                        } catch (Exception e) {
                            setSelection(getText().toString().length());
                        }
                        ToastUtils.showShort("输入内容违法，无法提交，请重新输入");
                        return;
                    }
                    for (int index = string.length() - 1; index >= 0; index--) {
                        String value = string.charAt(index) + "";
                        if (InputFilterUtils.getUnicode(value).equals("\\u2d")) {
                            continue;
                        }
                        Pattern p = Pattern.compile("[0-9|a-zA-Z|\u4e00-\u9fa5|,|.|*|·|:|@|?|!|，|。|、|？|！|（|）|(|)|\n|\u2013|\u002d|\uff0d|\uff1a|]+");
                        Matcher m = p.matcher(value);
                        if (!m.matches()) {
                            setText(string.replace(value, ""));
                            try {
                                setSelection(start);
                            } catch (Exception e) {
                                setSelection(getText().toString().length());
                            }
                            ToastUtils.showShort("不支持输入特殊字符以及表情");
                            break;
                        }
                        if ((boolean) SysUtil.checkSpecial(value).get("special_is")) {
                            setText(string.replace(value, ""));
                            try {
                                setSelection(start);
                            } catch (Exception e) {
                                setSelection(getText().toString().length());
                            }
                            ToastUtils.showShort("包含特殊字符“ " + SysUtil.checkSpecial(value).get("special_str") + " ”无法提交，请重新输入");
                            break;
                        }
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
        } else {

            InputFilter[] fileList;
            if (getFilters() != null && getFilters().length > 0) {
                fileList = new InputFilter[getFilters().length + 1];
                for (int i = 0; i < getFilters().length; i++) {
                    fileList[i] = getFilters()[i];
                }
                fileList[fileList.length - 1] = InputFilterUtils.setemojiFilter(getContext());
                setFilters(fileList);

            } else {
                fileList = new InputFilter[]{InputFilterUtils.setemojiFilter(getContext())};
                setFilters(fileList);
            }
            addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                    String string = getText().toString();
                    if (!TextUtils.isEmpty(SysUtil.checkSQL(string))) {
                        setText(string.replace(SysUtil.checkSQL(string), ""));
                        try {
                            setSelection(start);
                        } catch (Exception e) {
                            setSelection(getText().toString().length());
                        }
                        ToastUtils.showShort("输入内容违法，无法提交，请重新输入");
                        return;
                    }
                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
        }

    }

    boolean canCopy = false, canNewLine = false;
    private int filterType;

    private void setCanCopy(boolean canCopy) {
        this.canCopy = canCopy;
        if (!canCopy) {
            setCustomSelectionActionModeCallback(new ActionMode.Callback() {
                @Override
                public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                    return false;
                }

                @Override
                public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                    return false;
                }

                @Override
                public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                    return false;
                }

                @Override
                public void onDestroyActionMode(ActionMode mode) {

                }
            });
            setLongClickable(false);
            setTextIsSelectable(false);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                // call that method
                this.setCustomInsertionActionModeCallback(new ActionMode.Callback() {
                    @Override
                    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                        return false;
                    }

                    @Override
                    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                        return false;
                    }

                    @Override
                    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                        return false;
                    }

                    @Override
                    public void onDestroyActionMode(ActionMode mode) {

                    }
                });
            }
        }
    }


    @Override
    public boolean onTextContextMenuItem(int id) {
        if (id == 16908322 && !canCopy) {
            ToastUtils.showShort("不允许粘贴哦！");
            return false;
        }
        return super.onTextContextMenuItem(id);
    }

    /**
     * 设置过滤
     *
     * @param context
     * @return
     */
    public static InputFilter setFilter(Context context) {
        InputFilter emojiFilter = new InputFilter() {

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (TextUtils.isEmpty(source) || source.toString().length() == 0) return null;
                for (int index = start; index < end; index++) {
                    String value = source.charAt(index) + "";
                    String code = InputFilterUtils.getUnicode(value);
                    if (code.equals("\\u2d")) {
                        continue;
                    }
                    Pattern p = Pattern.compile("[0-9|a-zA-Z|\u4e00-\u9fa5|,|.|@|?|，|。|？|！|（|）|\u2013|\u002d|\uff0d|]+");
                    Matcher m = p.matcher(value);
                    if (!m.matches()) {
                        ToastUtils.showShort("不支持输入特殊字符以及表情");
                        return "";
                    }
                    if ((boolean) SysUtil.checkSpecial(value).get("special_is")) {
                        ToastUtils.showShort("包含特殊字符“ " + SysUtil.checkSpecial(value).get("special_str") + " ”无法提交，请重新输入");
                        return "";
                    }
                }
//                String speChat = "[`~#_$%^&*|{}':;'\\[\\]<>/~#￥%……&*（）— +|【】]";
//                Pattern pattern = Pattern.compile(speChat);
//                Matcher matcher = pattern.matcher(source.toString());
//                if (matcher.find()) {
//                    CustomToast.showToast(context, "不支持输入特殊字符", false);
//                    return "";
//                }
//                for (int index = start; index < end; index++) {
//                    int type = Character.getType(source.charAt(index));
//                    if (type == Character.SURROGATE) {
//                        CustomToast.showToast(context, "不支持输入表情", false);
//                        return "";
//                    }
//                }
                return null;
            }
        };
        return emojiFilter;
    }
}
